package com.code.user.controller;

import com.code.common.model.ResultVO;
import com.code.user.social.factory.GitHubSocialFactory;
import com.code.user.social.factory.GiteeSocialFactory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
 * Created by IntelliJ IDEA.
 *
 * @author: Yan
 * @date: 2023/4/13
 */
@Api(value = "社交登录控制器", description = "社交登录控制器")
@Slf4j
@Controller
@RequestMapping("/social")
public class SocialController {

    /***************************
     *          GitHub         *
     ***************************/
    @ApiOperation(value = "GitHub第三方登录页请求", notes = "GitHub第三方登录页请求")
    @SneakyThrows
    @GetMapping("/github/login")
    public void gitHubLogin(HttpServletResponse response){
        response.sendRedirect(new GitHubSocialFactory().producer().buildLoginUrl());
    }

    @ApiOperation(value = "GitHub登录回调拦截请求", notes = "GitHub登录回调拦截请求")
    @GetMapping("/github/callback")
    @ResponseBody
    public ResultVO<OAuth2AccessToken> gitHubCallback(@RequestParam("code") String code, @RequestParam("state") String state){
        OAuth2AccessToken oAuth2AccessToken = new GitHubSocialFactory().producer().buildOAuth2AccessToken(code, state);
        return ResultVO.OK(oAuth2AccessToken);
    }

    /***************************
     *          GitEE          *
     ***************************/
    @ApiOperation(value = "Gitee第三方登录页请求", notes = "Gitee第三方登录页请求")
    @SneakyThrows
    @GetMapping("/gitee/login")
    public void giteeLogin(HttpServletResponse response){
        response.sendRedirect(new GiteeSocialFactory().producer().buildLoginUrl());
    }

    @ApiOperation(value = "Gitee登录回调拦截请求", notes = "Gitee登录回调拦截请求")
    @GetMapping("/gitee/callback")
    @ResponseBody
    public ResultVO<OAuth2AccessToken> giteeCallback(@RequestParam("code") String code, @RequestParam("state") String state){
        OAuth2AccessToken oAuth2AccessToken = new GiteeSocialFactory().producer().buildOAuth2AccessToken(code, state);
        return ResultVO.OK(oAuth2AccessToken);
    }

}
